import 'package:flutter/material.dart';
import 'package:flutter_framework/assets/r_img.dart';
import 'package:flutter_framework/utils/screen_ui.dart';

const double dFactor = 0.6;

class DragViewPhoto extends StatefulWidget {
  @override
  _DragViewPhotoState createState() => _DragViewPhotoState();
}

/// todo功能
/// 1，双指拉伸放大
/// 2，双指拉伸缩小，最小比例是1，按照微信的功能做

class _DragViewPhotoState extends State<DragViewPhoto>
    with SingleTickerProviderStateMixin {
  Offset starOffset = Offset.zero;
  Offset moveOffset = Offset.zero;
  double closeOpc = 0.7;

  bool get isPop => opacity < closeOpc && lastDragAxis != AxisDirection.up;

  bool get isScaling => isScale || _scale != 1;

  /// animate moveOffset ,添加了阻尼效果的
  Offset animatedMoveOffset = Offset.zero;
  bool isDragging = false;

  bool isScale = false;
  double _scale = 1.0;
  double _previousScale = 1.0;

  // 计算阻尼效果
  double dampingFactor = dFactor; // 阻尼系数，可以调整这个值
  double opacity = 1;

  AxisDirection lastDragAxis = AxisDirection.down;
  late AnimationController animationCtrl = AnimationController(
      vsync: this, duration: const Duration(milliseconds: 400));

  @override
  void initState() {
    animationCtrl.addListener(() {
      if (!isPop) {
        /// 处理透明度
        double currentNum = 1 - opacity;
        double val = animationCtrl.value * currentNum;

        ///处理offset把 0-1的值映射到 offset的 Offset(300,300) => Offset.zero 上
        Offset prevOffset = animatedMoveOffset;
        Offset resetOffset = Offset(
            animatedMoveOffset.dx - (animationCtrl.value * prevOffset.dx),
            animatedMoveOffset.dy - (animationCtrl.value * prevOffset.dy));

        setState(() {
          opacity += val;
          animatedMoveOffset = resetOffset;
        });
        if (animationCtrl.status == AnimationStatus.completed) {
          animationCtrl.reset();
        }
      } else {
        /// 关闭页面 把背景opacity过渡回0
        double val = animationCtrl.value * opacity;
        setState(() {
          opacity = opacity - val;
        });
      }
    });

    super.initState();
  }

  @override
  void dispose() {
    animationCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return IgnorePointer(
      ignoring: isDragging,
      child: SizedBox(
        width: ScreenUI.width,
        height: ScreenUI.height,
        child: GestureDetector(
          onTap: () {
            if (!isDragging) {
              Navigator.pop(context);
            }
          },
          onScaleStart: (details) {
            print("两个手指触摸");
            _previousScale = _scale;
            isScale = true;
            setState(() {});
          },
          onScaleUpdate: (details) {
            setState(() {
              _scale = _previousScale * details.scale;
              if (_scale <= 1) {
                _scale = 1;
              }
            });
            print("当前的缩放值：${_scale}");
          },
          onScaleEnd: (_) {
            setState(() {
              isScale = false;
            });
          },
          onVerticalDragDown: (DragDownDetails detail) {
            starOffset = detail.localPosition;

            ///判断触摸点的位置，动态设置阻尼系数
            if (starOffset.dy > ScreenUI.height / 2 - 50) {
              dampingFactor = 1;
            } else {
              dampingFactor = dFactor;
            }
          },
          onVerticalDragUpdate: (detail) {
            if (!isDragging) {
              isDragging = true;
            }
            moveOffset = detail.localPosition - starOffset;

            if (moveOffset.dy > 0) {
              ///向下drag
              ///半屏的高度设置透明度
              double _opcity = moveOffset.dy / (ScreenUI.height * (2 / 3));
              opacity = _opcity > 1 ? 0 : (1 - _opcity);
            }

            /// drag偏移量添加阻尼效果

            setState(() {
              if (detail.delta.dy >= 0) {
                lastDragAxis = AxisDirection.down;
              } else {
                lastDragAxis = AxisDirection.up;
              }
              moveOffset = moveOffset;
              animatedMoveOffset =
                  Offset(moveOffset.dx, moveOffset.dy * dampingFactor);
            });
          },
          onVerticalDragEnd: (detail) {
            animationCtrl.forward();
            if (isPop) {
              Navigator.pop(context);
            }
            isDragging = false;
          },
          child: ColoredBox(
            color: Colors.black.withOpacity(opacity),
            child: Center(
              child: Transform(
                alignment: Alignment.center,
                transform: Matrix4.identity()
                  ..translate(animatedMoveOffset.dx, animatedMoveOffset.dy)
                  ..scale(
                      // isScaling
                      //     ? _scale
                      //     :
                      opacity < 0.3 ? 0.3 : opacity,
                      // isScaling
                      //     ? _scale
                      //     :
                      opacity < 0.3 ? 0.3 : opacity),
                child: Hero(
                  tag: "wx_icon_hero",
                  child: Image.asset(
                    ImgR.imgUserserWxIcon,
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
